package com.cat.binaryTree;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree/description/
 * @create 2025/9/29 11:42
 * @since JDK17
 */

public class Solution85 {
    public int maxLevelSum(TreeNode root) {
        int ans = 0, sum = 0, tot = Integer.MIN_VALUE, x = 0;
        Deque<TreeNode> q = new ArrayDeque<>();
        q.add(root);
        while (!q.isEmpty()) {
            sum = 0;
            x++;
            for (int i = 0, end = q.size(); i < end; i++) {
                var p = q.poll();
                sum += p.val;
                if (p.left != null) {
                    q.add(p.left);
                }
                if (p.right != null) {
                    q.add(p.right);
                }
            }
            if (sum > tot) {
                ans = x;
                tot = sum;
            }
        }

        return ans;
    }
}
